<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\FinanceAgentj;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\FinanceJd;
use App\Http\Services\FinanceServices;

class AgentdAutoCronTabCommand extends Command
{

    protected $signature = 'agentdAutoCronTabCommand';

    protected $description = '代理金豆红包自动领取';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $agentj_model = new FinanceAgentj();
        $model_finance_user_wallet = new FinanceUserWallet();
        $jd_model = new FinanceJd();
        $financeServices = new FinanceServices();

        $now = time();

        do {
            //获取需要自动发放未领取的代理金豆转入记录
            $list = $agentj_model->getAgentJdLogByType($now);
            foreach($list as $logInfo) {
                //暂停代理操作
                $cacheKey = 'USER:AGENTJDRECEIVE:'.$logInfo['id'];
                if (!redis_lock($cacheKey, 10)) {
                    continue;
                }
                $config = config('pay');
                $jd_desc = $config['wallet_change_desc']['jd_agentj_into'];

                //用户钱包
                $wallet = $model_finance_user_wallet->get_wallet($logInfo['user_id']);
                //修改前用户的娱乐值
                $game_balance = empty($wallet['game_balance']) ? 0 : $wallet['game_balance'];

                DB::beginTransaction();
                try {
                    //更新记录
                    $agentj_model->updateAgentJdLog($logInfo['id'], ['agentd_type'=>2]);
    
                    //增加
                    $jd_model->inc($logInfo['user_id'], $logInfo['id'], 5, $logInfo['jd_num'], $jd_desc);
    
                    DB::commit();
                } catch (\Exception $e) {
                    write_log('error_agentdAutoCronTabCommand', '数据更新异常', ['msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                    DB::rollBack();
                    redis_unlock($cacheKey);
                    continue;
                }
                redis_unlock($cacheKey);
    
                //娱乐等级处理
                $financeServices->_userGameRankLevelPrivilege($logInfo['user_id']);
    
                //用户娱乐等级升级全服公告
                $financeServices->_userGameRankLevelNotice($logInfo['user_id'], $game_balance);
            }
        } while (false);
    }

}